/**
 * 定义DataValidationController数据有效性模块
 */
(function(window, angular, undefined){
	/**
	* 定义DataValidationController数据有效性模块
	*/
	var DataValidationController = angular.module('water.apps.WasteWater.dataTransValidation.DataValidationController', ['ui.router','itfreer','waterCommon',
		                                                                                                                   'water.common.dateUtil']);
	//有效性审核历史记录
	DataValidationController.controller('OperationHistoryController',function($NavService,$sce,$scope,$itfreerHttp,$itfreer,$compile,$http,$waterDataCommon,
																				$httpData,$dateUtil,$queryObj,$wdp,$rootScope,$state,$formObject){
		$NavService.setSelectedTabSecond("DataValidationHistory");
		$wdp.viewValue.DataValidationList={};
		$scope.transferValidate={};
		$queryObj.quertHistory={};
		var yearlist=$scope.yearlist={};
		yearlist.year=[];
		$scope.isQuery=true;
		var nowDate = new Date();
		var y=nowDate.getFullYear();
		for(var i=0;i<4;i++){
			var obj=new Object();
			obj.name=y-i+"年"
			obj.value=y-i+"";
			yearlist.year.push(obj);
		};
		$queryObj.quertHistory.st=y-1+"";
		$queryObj.quertHistory.et=y+"";
		$scope.getDataValidationHistory=function(){
			$queryObj.quertHistory.WWTPID=$wdp.viewValue.wwtpDetailParm.WWTPID;
			$queryObj.quertHistory.CODE="";
			$waterDataCommon.getPageRows("/DataValidation/getDataValidationHistory.do","DataValidationHistoryList",$queryObj.quertHistory,100,1,function(d){
				
			});
		};
		
		$scope.newSelfTest=function(){
			$wdp.viewValue.DataValidationList={};
			$state.go('DataValidation');
		};
		
		$scope.openSelfTest=function(val){
			$wdp.viewValue.DataValidationList.CODE=val.CODE;
			$wdp.viewValue.DataValidationList.GUID=val.GUID;
			$wdp.viewValue.DataValidationList.WWTPID=val.WWTP_ID;
			$wdp.viewValue.DataValidationList.DATATIME =val.DATATIME;
			$state.go('DataValidation');
		};
		if($wdp.viewValue.wwtpDetailParmWatch){
			$wdp.viewValue.wwtpDetailParmWatch();
		}
		$wdp.viewValue.wwtpDetailParmWatch = $rootScope.$watch(function(){return $wdp.viewValue.wwtpDetailParm;},function(){
			if(!$wdp.viewValue.wwtpDetailParm){
				return;
			}
			$scope.getDataValidationHistory();
        },true);
		
	});
	
	/**
	 *  在线监测数据有效性
	 */
	DataValidationController.controller('ValidationMonitorDataStatisticsController',function($filter,$stateParams,$sce,$ReportService,$scope,$itfreerHttp,$itfreer,$compile,$http,$waterDataCommon,$httpData,$dateUtil,$queryObj,$wdp,$rootScope,$state,$formObject,$NavService,OperationStationJobService,$DataReportService){
		$NavService.setSelectedTab("DataTransValidate.Statistics");
		//去掉视频延迟函数
		if($wdp.timeout){
			clearTimeout($wdp.timeout); 
		}
		$scope.needGoback=false;
		var strWwtpIDs = "";			// 污染源ID
		var strFlowName = "1";			// 流向类型(默认出水口)
		var myDate = new Date();
		$scope.manual="";
		$("#listdata").idTabs();		// tab页初始化
		//控制选择统计周期
		$scope.dataType="week";
		$scope.yearlist=[];
		var currentYear=(new Date()).getFullYear();
		for(var i=0;i<4;i++){
			$scope.yearlist.push({
				name:currentYear-i+"年",
				value:currentYear-i+""
			});
		}; 
		$scope.selectYear=currentYear+"";
		//改变统计周期
		$scope.dataTypeChange = function(dataType){
			$scope.dataType = dataType;
			$scope.getMonitorDataValidationStatisticsTotal();
		}
		// 选择年份更新周信息
		$scope.changeYear = function(year){
			$scope.weeklist = $DataReportService.getYearWeek(year);
			$scope.selectWeek= $scope.weeklist[0].value;
			for(var i=0;i<$scope.weeklist.length;i++){
				var week = $scope.weeklist[i];
				if(week.today){
					$scope.selectWeek = week.value;
				}
			}
		}
		$scope.changeYear($scope.selectYear);
		//控制是否显示运维事件
		$scope.showEvent=false;
		$scope.queryFlag="";
		$scope.isShowEvent=function(str){
			$scope.queryFlag=str;
			$scope.getMonitorDataValidationStatisticsTotal();
			if(str=='0'){
				$scope.showEvent=true;
			}
			else{
				$scope.showEvent=false;
			}
		};
		//$scope.viewFrom = "DataValidation_Statistics";
		$scope.viewFrom = "DataValidationQuarter";
		$scope.operationJobs = [];
		var listDivHeight = $wdp.Map_H - 250;
		$scope.listDivStyle = {overflow:'auto',height:listDivHeight+"px"};
		
		var selectedJob = {GUID:'all',JOB_CODE:'all',JOB_NAME:'全部',selected:true};
		OperationStationJobService.postQuery("/Operation/getOperationJobs.do",{},100,1).then(function(data){
			angular.forEach(data.data,function(value,key){
				value.selected=false;
			})
			var jobdata=[];
			for(var i=0;i<data.data.length;i++){
				var obj=data.data[i];
				if(obj.JOB_NAME=='现场考核'||obj.JOB_NAME=='人工监测'){
				}
				else{
					jobdata.push(obj);
				}
			}
			$scope.operationJobs = jobdata;
			$scope.operationJobs.splice(0,0,selectedJob);
			
		});
		$scope.toggleJob=function(jobid){
			$scope.jobId = jobid;
		};
		
		$scope.dailyInspectionType=[];
		OperationStationJobService.postQuery("/DailyInspection/getInspectionType.do",{level:1}).then(function(data){
			angular.forEach(data.data,function(value,key){
				value.selected=false;
			});
			$scope.dailyInspectionType =  data.data;
			$scope.dailyInspectionType.splice(0,0,{S_DOMAINCODE:'all',S_DOMAINCAPTION:'全部',selected:true})
		});
		//控制显示参数
		$scope.showParam=false;
		$scope.PARAM_NAME="全部";
		$scope.toggleInspectionType = function(row){
			$scope.subType = row.S_DOMAINCODE;
		}
		        
        $scope.queryObject={};
        $scope.queryObject.queryMonitorDataValidation={};
        $scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR = myDate.getFullYear();
        $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH = 1;
        $scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH = myDate.getMonth()+1;
        getQuarterStartMonth();
        //获取当前月的开始月份
        function  getQuarterStartMonth(){
        	var now = new Date(); //当前日期 
        	var nowMonth = now.getMonth()+1; //当前月
        	var quarterStartMonth = 0; 
        	if(nowMonth<4){ 
        	quarterStartMonth = 1; 
        	} 
        	if(3<nowMonth && nowMonth<7){ 
        	quarterStartMonth = 4; 
        	} 
        	if(6<nowMonth && nowMonth<10){ 
        	quarterStartMonth = 7; 
        	} 
        	if(nowMonth>9){ 
        	quarterStartMonth = 10; 
        	} 
        	 $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH= quarterStartMonth+1;
        	 $scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH=quarterStartMonth+2;
        }      
      //监听左侧参数变化
		$scope.$on('dataPramChanged', function(event, data) {
			$wdp.viewValue.wwtpDetailParm=data;
			if(!$scope.jobId){
				$scope.jobId = "all";
			}
			if(!$scope.subType){
				$scope.subType = "all";
			}
			 $scope.manual=false;
			$scope.getMonitorDataValidationStatisticsTotal();
	    });
		
		//监测点流向类型(进水口/出水口)
		$scope.getFlowName=function(orgid){
			strFlowName = orgid;
			var li = $("#FlowNameUL li[orgid='"+orgid+"']");
			var notli = $("#FlowNameUL li[orgid!='"+orgid+"']")
			if(!li.hasClass("selected"))
			{
				li.addClass('selected');
				notli.removeClass('selected');
			}	
		};
		
		$scope.validation = {};
		$scope.validation.isLoading = false;
		
		// 查看任务有效性列表
		$scope.taskValidationList = [];
		$scope.getValidationDetailList = function(curRow){
				$wdp.viewValue.DataValidationParm = {};
				$wdp.viewValue.DataValidationParm.flowType = $("#FlowNameUL li.selected").attr("orgid");
				$wdp.viewValue.DataValidationParm.startTime =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-01" + " 00:00:00";
				//获取每个月最后一天
				var end_day = new Date($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR,$scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH,0); 
				$wdp.viewValue.DataValidationParm.endTime =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-"+end_day.getDate() + " 23:59:59";
				
				
				$wdp.viewValue.DataValidationParm.job = curRow.JOB_ID;
				$wdp.viewValue.DataValidationParm.WWTPID=$wdp.viewValue.wwtpDetailParm.WWTPID;
				$("#validationList").hide();
				$("#taskList").show();
				$state.go($scope.viewFrom+".TaskQuery");
				$scope.needGoback = true;
				return;
		}
		
		
		/**
		 * 流量计算
		 */
		$scope.getTotalFlow = function (){
			$waterDataCommon.getPageRows("/MonitorDataValidate/getWWTPFlow.do", 
					"WWTPFlowList",$scope.queryObject.queryMonitorDataValidation,10,1);
		}
		$scope.viewFlowImage = function(curRow){
			var src = 'http://202.105.247.6:8082';
			src += $filter('firstImgUrl')(curRow.IMG);
			imgShowUrl(src);
		}	
		
		// 查询日常巡检或定期维护分项的有效性
		$scope.queryJobTypeValidationList=function(queryObject){
			$waterDataCommon.getPageRows("/MonitorDataValidate/queryDailyInspectionTypeValidationList.do", "JobValidationList",queryObject,0,0, function(d){
				if (d && d.length>0 ){
					angular.forEach(d,function(value,key){
						var validation = {};
						validation.JOB_ID = value.JOB_ID;
						validation.JOB_NAME = value.JOB_NAME; //value.JOB_NAME
						validation.PARAM_NAME = value.JOB_TYPE;
						validation.PARAM_ID = value.PARAM_ID;
						validation.TIME_REQUIRE = value.JOB_CYCLE_DESC;
						validation.TASK_TOTAL = value.JOB_TASK_TOTALNUM;
						validation.FINISHED_TOTAL = value.JOB_TASK_COMPLETENUM;
						validation.TASK_INTIME = value.JOB_TASK_TIMELYNUM;
						validation.TASK_INTIMEPERCENT =  value.JOB_TASK_TIMELYNUM/value.JOB_TASK_TOTALNUM;
						validation.PASSED_PERCENT = value.JOB_TASK_PASSNUM/value.JOB_TASK_TOTALNUM;
						validation.VALIDATION_RESULT = value.JOB_VALIDATION_DESC;
						$scope.validationList.push(validation);	
					});
				}
				
				$scope.validation.isLoading = false;
			});
		}
		
		function parseYearStartMonth(year,month){
			var start_month = ''+ month;
			
			if(start_month.length==1) {
				start_month = '0' + start_month;
			}
			
			var start_date = year + '-' + start_month + '-01';
			return start_date;
		}
		
		function parseYearEndMonth(year, month){
			
			var end_day = new Date(year,month,0); 
			var endday = '' + end_day.getDate();
			
			if(endday.length==1){
				endday = '0' + endday;
			}
			var end_month = '' + month;
			if(end_month.length==1) {
				end_month = '0' + end_month;
			}
			
			var end_date = year + '-' + end_month + '-' + endday;
			return end_date;
		}
		
		
		//获取所有运维任务统计  wangl 2016.6.24
		$scope.getAllTaskStatistics=function(data){
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/getAllTaskStatistics.do","hd",data,100,1,function(d){
				$scope.validationList=d.data;
				$scope.validation.isLoading = false; 
			});
		};
		//获取单个任务统计
		$scope.getOneTaskStatistics=function(data){
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/getOneTaskStatistics.do","hd",data,100,1,function(d){
				$scope.validationList=d.data;
				$scope.validation.isLoading = false; 
			});
		};
		var nowday = myDate.getDate(); //当前日 
		var nowmonth = myDate.getMonth()+1; //当前月 
		var nowyear = myDate.getFullYear(); //当前年 
		var h=myDate.getHours();//当前小时
		var mi=myDate.getMinutes();//当前分
		var se=myDate.getSeconds();//当前秒
		//获取设备故障率
		$scope.getOperationRate=function(data){
			if(Number($scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH)>nowmonth){
				data.END_TIME=nowyear+"-"+nowmonth+"-"+nowday+" "+h+":"+mi+":"+se;
			}
			else{
				//data.END_TIME=$scope.queryObject.queryMonitorDataValidation.END_TIME;
				data.END_TIME=parseYearEndMonth($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR, $scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH)+" 23:59:59";
			}
			if($scope.dataType=="week"){
				var weekInfo=$scope.selectWeek.split(",");
				data.START_TIME = weekInfo[0] + " 00:00:00";
				data.END_TIME = weekInfo[1] + " 23:59:59";
			}
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/getOperationRate.do","hd",data,100,1,function(d){
				$scope.deviceOprRateList=d.data;
				$scope.validation.isLoading = false; 
			});
			
		};
		//获取数采仪在线率
		$scope.getDataLoggerRate=function(data){
			if(Number($scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH)>nowmonth){
				data.END_TIME=nowyear+"-"+nowmonth+"-"+nowday+" "+h+":"+mi+":"+se;
			}
			else{
				//data.END_TIME=$scope.queryObject.queryMonitorDataValidation.END_TIME;
				data.END_TIME=parseYearEndMonth($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR, $scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH)+" 23:59:59";
			}
			if($scope.dataType=="week"){
				var weekInfo=$scope.selectWeek.split(",");
				data.START_TIME = weekInfo[0] + " 00:00:00";
				data.END_TIME = weekInfo[1] + " 23:59:59";
			}
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/getDataLoggerRate.do","hd",data,100,1,function(d){
				$scope.mnOnlineRate=d.data[0];
				$scope.validation.isLoading = false; 
			});
		};
		//获取数据传输率
		$scope.computeDataTransferRate=function(data){
			if($scope.dataType=="week"){
				var weekInfo=$scope.selectWeek.split(",");
				data.START_TIME = weekInfo[0] + " 00:00:00";
				data.END_TIME = weekInfo[1] + " 23:59:59";
			}
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/getEfficient.do","hd",data,100,1,function(d){
				if(d.data.length>0) {
					$scope.transferValidate=d.data[0];
				} else {
					$scope.transferValidate=null;
				}
				$scope.validation.isLoading = false; 
			});
		};
		//直接从表里面查询已经计算好的传输有效率
		$scope.queryDataTransferRate=function(data){
			if($scope.dataType=="week"){
				var weekInfo=$scope.selectWeek.split(",");
				data.START_TIME = weekInfo[0] + " 00:00:00";
				data.END_TIME = weekInfo[1] + " 23:59:59";
			}
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/queryEfficient.do","hd",data,100,1,function(d){
				if(d.data.length>0) {
					$scope.transferValidate=d.data[0];
				} else {
					$scope.transferValidate=null;
				}
				$scope.validation.isLoading = false; 
			});
		};
		//时间验证
		$scope.checkErr = function(curRow){	
			if(typeof curRow.NO_POWER_START_TIME!="" && typeof curRow.NO_POWER_END_TIME!="" && curRow.NO_POWER_START_TIME!=undefined && curRow.NO_POWER_END_TIME!=undefined)
			{
			    if((new Date(curRow.NO_POWER_START_TIME.replace(/-/g,"\/"))) > (new Date(curRow.NO_POWER_END_TIME.replace(/-/g,"\/")))){
			    	$.messager.alert("提示","开始时间不能大于结束时间");
			    	$scope.isQuery=false;
			    	return ;
			    }else {
			    	$scope.isQuery=true;
			    }
			    var startTime="";
			    var endTime="";
			    if($scope.dataType=="week") {
					var weekInfo=$scope.selectWeek.split(",");
				    startTime = weekInfo[0]+" 00:00:00";
				    endTime = weekInfo[1]+" 23:59:59";
			    }
			    else {
			    	startTime =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-01" + " 00:00:00";
					//获取每个月最后一天
					var end_day = new Date($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR,$scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH,0); 
					endTime =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-"+end_day.getDate() + " 23:59:59";
			    }
			    var flag = isDateBetween(curRow.NO_POWER_START_TIME,startTime,endTime);
			    var flag1 = isDateBetween(curRow.NO_POWER_END_TIME,startTime,endTime);
			    if(!(flag && flag1)) {
			    	$scope.isQuery=false;
			    	$.messager.alert("提示","停产停排日期不能在所选日期之外");
			    	return ;
			    } else {
			    	$scope.isQuery=true;
			    }
			}
		 };
		 $scope.onManualClick = function() {
			 $scope.manual=true;
			 $scope.getMonitorDataValidationStatisticsTotal();
		 }
		 //时间对比
		 function  dateCompare(dateString, compareDateString){  
		    var dateTime = dateParse(dateString).getTime();  
		    var compareDateTime = dateParse(compareDateString).getTime();  
		    if(compareDateTime > dateTime){  
		        return 1;  
		    }else if(compareDateTime == dateTime){  
		        return 0;  
		    }else{  
		        return -1;  
		    } 
		 };
		 /** 
		  * 判断日期是否在区间内，在区间内返回true，否返回false 
		  * @param dateString 日期字符串 
		  * @param startDateString 区间开始日期字符串 
		  * @param endDateString 区间结束日期字符串 
		  * @returns {Number} 
		  */  
		 function isDateBetween(dateString, startDateString, endDateString){    
			 if(dateString =='') {
				 return true;
			 }
		     var flag = false;  
		     var startFlag = (dateCompare(dateString, startDateString) < 1);  
		     var endFlag = (dateCompare(dateString, endDateString) > -1);  
		     if(startFlag && endFlag){  
		         flag = true;  
		     }  
		     return flag;  
		 }; 
		/**日期解析，字符串转日期 
		 * @param dateString 可以为2017-02-16，2017/02/16，2017.02.16 
		 * @returns {Date} 返回对应的日期对象 
		 * 
		 */
		function dateParse(dateString){  
		    var SEPARATOR_BAR = "-";  
		    var SEPARATOR_SLASH = "/";  
		    var SEPARATOR_DOT = "."; 
		    var flag = /-/g;
		    var dateArray;  
		    if(dateString.indexOf(SEPARATOR_BAR) > -1){  
		        dateArray = dateString.replace(flag,SEPARATOR_SLASH);  
		    }else {
		    	dateArray = dateString;
		    }
		    return new Date(dateArray);   
		}; 
		$scope.queryNoPowerTimeByStationID = function() {
			 $scope.noPowerList="";
			 $scope.queryObject.STATION_ID=$wdp.viewValue.wwtpDetailParm.STATION_ID;
				$scope.queryObject.START_TIME =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-01" + " 00:00:00";
				//获取每个月最后一天
				var end_day = new Date($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR,$scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH,0); 
				$scope.queryObject.END_TIME =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-"+end_day.getDate() + " 23:59:59";
				$scope.queryObject.DATA_TYPE = $scope.dataType;
				if($scope.dataType=="week"){
					var weekInfo=$scope.selectWeek.split(",");
					$scope.queryObject.START_TIME = weekInfo[0] + " 00:00:00";
					$scope.queryObject.END_TIME = weekInfo[1] + " 23:59:59";
				}
				$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/queryNoPowerByStationId.do","noPowerList",$scope.queryObject,100,1,function(d){
					if(d) {
						var length = d.data.length;
						var timeNameArray=[];
						if(length>0){
							for(var i =0;i<d.data.length;i++) {
								var name = i+1;
								timeNameArray.push(parseInt(name));
								if(d.data[i].TIME_NUM == null)
								{	
									d.data[i].TIME_NUM="停电时段"+name.toString();
								}
							}
							timeNameArray.sort(sortNumber);
							length = parseInt(timeNameArray[length-1])+parseInt(1);
							d.data.push({isNew:true,MN:$scope.queryObject.STATION_ID,TIME_NUM:'停电时段'+length});
						} else {
							d.data.push({isNew:true,MN:$scope.queryObject.STATION_ID,TIME_NUM:'停电时段1'});
						}
						$scope.noPowerList=d.data;
					}
				});
		}
		function sortNumber(a,b) 
		{ 
		return a - b 
		} 
		//获取日常巡检单项统计
		$scope.getInspectionSubkey=function(data){
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/getInspectionSubkey.do","hd",data,100,1,function(d){
				$scope.validationList=d.data;
				$scope.validation.isLoading = false; 
			});
		};
		// 在线监测数据有效性统计
		$scope.validationList = [];
		$scope.getMonitorDataValidationStatisticsTotal=function(flag){
			if(flag=='0') {
				$scope.manual=false;
			}
			
			if($scope.viewFrom=='DataValidation.Statistics'){
				strWwtpIDs=$scope.wsclcid;
				strFlowName=$scope.flowType;
				$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR=$scope.year;
				$scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH=$scope.startDate;
				$scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH=$scope.endDate ;
			}
			var start_time="";
			var end_time="";
			var flag = /\//g;
			//查询停电时间
			$scope.queryNoPowerTimeByStationID();
			var startArray=[];
			var endArray=[];
			if($scope.noPowerList.length>0) {
				for(var k =0;k<$scope.noPowerList.length;k++) {
					var st_index=0;
					var end_index=0;
					if($scope.noPowerList[k].NO_POWER_START_TIME==null ||$scope.noPowerList[k].isNew==true) {
						continue;
					}
					if($scope.noPowerList[k].NO_POWER_END_TIME==null) {
						continue;
					}
					st_index = $scope.noPowerList[k].NO_POWER_START_TIME.indexOf("/");
					end_index = $scope.noPowerList[k].NO_POWER_END_TIME.indexOf("/");
					if(st_index>0) {
						$scope.noPowerList[k].NO_POWER_START_TIME = $scope.noPowerList[k].NO_POWER_START_TIME.replace(flag,"-");
						$scope.noPowerList[k].NO_POWER_START_TIME=$scope.noPowerList[k].NO_POWER_START_TIME+":00";
					}
					if(end_index>0) {
						$scope.noPowerList[k].NO_POWER_END_TIME = $scope.noPowerList[k].NO_POWER_END_TIME.replace(flag,"-");
						$scope.noPowerList[k].NO_POWER_END_TIME=$scope.noPowerList[k].NO_POWER_END_TIME+":00";
					}
					start_time += $scope.noPowerList[k].NO_POWER_START_TIME+",";
					startArray.push($scope.noPowerList[k].NO_POWER_START_TIME);
					end_time += $scope.noPowerList[k].NO_POWER_END_TIME+",";
					endArray.push($scope.noPowerList[k].NO_POWER_END_TIME);
				}
			}
			$scope.validation.isLoading = true;
			
			$scope.queryObject.queryMonitorDataValidation.WWTP_ID=strWwtpIDs;
			$scope.queryObject.queryMonitorDataValidation.JOB_ID=$scope.jobId;
			$scope.queryObject.queryMonitorDataValidation.INSPECTION_TYPE = $scope.subType;
			$scope.queryObject.queryMonitorDataValidation.FLOW_NAME=strFlowName;
			$scope.queryObject.queryMonitorDataValidation.STATION_ID=$wdp.viewValue.wwtpDetailParm.STATION_ID;
			
			$scope.queryObject.queryMonitorDataValidation.ERROR_START_TIME=start_time;
			$scope.queryObject.queryMonitorDataValidation.ERROR_END_TIME=end_time;
			$scope.queryObject.queryMonitorDataValidation.AUTO_OR_MANUAL=$scope.manual;
			
			// 年份/月份为日期
			$scope.queryObject.queryMonitorDataValidation.START_TIME =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-01" + " 00:00:00";
			//获取每个月最后一天
			var end_day = new Date($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR,$scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH,0); 
			$scope.queryObject.queryMonitorDataValidation.END_TIME =$scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR + "-" + $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH + "-"+end_day.getDate() + " 23:59:59";
			
			
			$scope.queryObject.queryMonitorDataValidation.DATA_TYPE = $scope.dataType;
			if($scope.dataType=="week"){
				var weekInfo=$scope.selectWeek.split(",");
				$scope.queryObject.queryMonitorDataValidation.START_TIME = weekInfo[0] + " 00:00:00";
				$scope.queryObject.queryMonitorDataValidation.END_TIME = weekInfo[1] + " 23:59:59";
			}
			$scope.validationList = [];		
			if($scope.queryFlag=="1") {
				$scope.getOperationRate($scope.queryObject.queryMonitorDataValidation);//设备故障率
			}else if ($scope.queryFlag=="2"){
				$scope.getDataLoggerRate($scope.queryObject.queryMonitorDataValidation);//数采仪在线率
			} else if ($scope.queryFlag=="0"){
				$scope.queryObject.queryMonitorDataValidation.HOUR="1";
				if($scope.manual==true) {
					var flag = checkTimeOverLap(startArray,endArray);
					if(flag==false) {
						return;
					}
					flag = checkTimeDouble(null,$scope.noPowerList);
					if(flag==false) {
						return;
					}
					$scope.computeDataTransferRate($scope.queryObject.queryMonitorDataValidation);//计算传输有效率
				} else {
					$scope.queryDataTransferRate($scope.queryObject.queryMonitorDataValidation);//查询传输有效率
				}
			}
			else{
				$scope.queryDataTransferRate($scope.queryObject.queryMonitorDataValidation);//查询传输有效率
			}
		 };
		//如果是从有效性审核跳转过来，把导航条移除 
		if($stateParams.viewFrom == "DataTransValidate.Statistics"){
			$("#ValidationDetail #DataValidationSecond").remove();
			$scope.viewFrom = $stateParams.viewFrom;
			$scope.jobId = $stateParams.jobId;
			$scope.startDate = $stateParams.startDate;
			$scope.endDate = $stateParams.endDate;
			$scope.wsclcid = $stateParams.wsclcid;
			$scope.flowType = $stateParams.flowType;
			$scope.year = $stateParams.year;
			$scope.getFlowName($stateParams.flowType);
			$scope.subType = $stateParams.subType;//日常巡检子项
			if($stateParams.listdataType=='DeviceOperation'){
				$("a[href='#DeviceOperation']").click();
			}
			if($stateParams.listdataType=='MNOnline'){
				$("a[href='#MNOnline']").click();
			}
			if($stateParams.listdataType=='DataTransfer'){
				$("a[href='#DataTransfer']").click();
			}
			$scope.needGoback=true;
		}
		$scope.goback = function(){
			$("#SelfValidationStep").show();
			$("#validationList").hide();
			$state.go("DataValidation");
			$scope.needGoback = false;
			$wdp.viewValue.DataValidationParm = null;
		}
		/**
		 * 新增停电时间段
		 */
		$scope.onSubmitCreateNoPowerClick = function(mn,curData){
			$saveObj={};
			$saveObj.STATION_ID = mn;
			$saveObj.NO_POWER_START_TIME = curData.NO_POWER_START_TIME;
			$saveObj.NO_POWER_END_TIME = curData.NO_POWER_END_TIME;
			$saveObj.TIME_NUM = curData.TIME_NUM;
			
			//格式化日期格式，如果日期格式为2017/07/24 改为2017-07-24
			var flag = /\//g;
			var st_index=0;
			var end_index=0;
			st_index = $saveObj.NO_POWER_START_TIME.indexOf("/");
			end_index = $saveObj.NO_POWER_END_TIME.indexOf("/");
			if(st_index>0) {
				$saveObj.NO_POWER_START_TIME = $saveObj.NO_POWER_START_TIME.replace(flag,"-");
				$saveObj.NO_POWER_START_TIME=$saveObj.NO_POWER_START_TIME+":00";
			}
			if(end_index>0) {
				$saveObj.NO_POWER_END_TIME = $saveObj.NO_POWER_END_TIME.replace(flag,"-");
				$saveObj.NO_POWER_END_TIME=$saveObj.NO_POWER_END_TIME+":00";
			}
			//校验是否为空
			var flag = true;
			flag = checkNull($saveObj);
			
			if(flag==false) {
				return;
			}
			//校验
			var startArray=[];
			var endArray=[];
			if($scope.noPowerList.length>0) {
				for(var k =0;k<$scope.noPowerList.length;k++) {
					if($scope.noPowerList[k].NO_POWER_START_TIME==null) {
						continue;
					}
					if($scope.noPowerList[k].NO_POWER_END_TIME==null) {
						continue;
					}
					var flag = /\//g;
					var st_index=0;
					var end_index=0;
					st_index = $scope.noPowerList[k].NO_POWER_START_TIME.indexOf("/");
					end_index = $scope.noPowerList[k].NO_POWER_END_TIME.indexOf("/");
					if(st_index>0) {
						$scope.noPowerList[k].NO_POWER_START_TIME = $scope.noPowerList[k].NO_POWER_START_TIME.replace(flag,"-");
						$scope.noPowerList[k].NO_POWER_START_TIME=$scope.noPowerList[k].NO_POWER_START_TIME+":00";
					}
					if(end_index>0) {
						$scope.noPowerList[k].NO_POWER_END_TIME = $scope.noPowerList[k].NO_POWER_END_TIME.replace(flag,"-");
						$scope.noPowerList[k].NO_POWER_END_TIME=$scope.noPowerList[k].NO_POWER_END_TIME+":00";
					}
					startArray.push($scope.noPowerList[k].NO_POWER_START_TIME);
					endArray.push($scope.noPowerList[k].NO_POWER_END_TIME);
				}
			}
			//校验新增的日期是否存在重复
			flag = checkTimeOverLap(startArray,endArray);
			if(flag==false) {
				return;
			}
			flag = checkTimeDouble(curData,$scope.noPowerList);
			if(flag==false) {
				return;
			}
			$waterDataCommon.createModel("BC_SNP_INFO",$saveObj).then(function(){
				$.messager.alert("保存成功","保存成功",'info');
				$scope.queryNoPowerTimeByStationID();
			});
		}
		
		/**
		 * 更新停电时间段
		 */
		$scope.onSubmitEditTimeSpanClick = function(curData){
			var updateData={};
			//校验是否为空
			if(!checkAllNull(curData)){
				return;
			}
			//校验
			var startArray=[];
			var endArray=[];
			if($scope.noPowerList.length>0) {
				for(var k =0;k<$scope.noPowerList.length;k++) {
					var start = $scope.noPowerList[k].NO_POWER_START_TIME;
					var end = $scope.noPowerList[k].NO_POWER_END_TIME
					if(start==null) {
						continue;
					} else {
						var flag = /\//g;
						var st_index=0;
						st_index = start.indexOf("/");
						if(st_index>0) {
							start = start.replace(flag,"-");
							start=start+":00";
						}
					}
					if(end==null) {
						continue;
					} else {
						var flag = /\//g;
						var end_index=0;
						end_index = end.indexOf("/");
						if(end_index>0) {
							end = end.replace(flag,"-");
							end=end+":00";
						}
					}
					startArray.push(start);
					endArray.push(end);
					$scope.noPowerList[k].NO_POWER_START_TIME = start;
					$scope.noPowerList[k].NO_POWER_END_TIME = end;
				}
			}
			//校验新增的日期是否存在重复
			flag = checkTimeOverLap(startArray,endArray);
			if(flag==false) {
				return;
			}
			flag = checkTimeDouble(curData,$scope.noPowerList);
			if(flag==false) {
				return;
			}
			curData.UPDATE_TIME = $dateUtil.formatDate(new Date(),"yyyy-MM-dd hh:mm:ss");
			curData = formateDate(curData);
			updateData.GUID = curData.GUID;
			updateData.NO_POWER_START_TIME = curData.NO_POWER_START_TIME;
			updateData.NO_POWER_END_TIME = curData.NO_POWER_END_TIME;
			updateData.UPDATE_TIME = curData.UPDATE_TIME;
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/updateNoPowerTime.do","hd",updateData,function(d) {
				$.messager.alert("保存成功","保存成功",'info');
			});
			$scope.queryNoPowerTimeByStationID();
		}
		
		/**
		 * 删除停电时间段
		 */
		$scope.onDeleteTimeSpanClick = function(curData){
			$waterDataCommon.getPageRows("/IndusteryPollutQuarterDataValidation/deleteNoPowerTime.do","hd",curData,function(d) {
				$.messager.alert("删除成功","删除成功",'info');
			});
			$scope.queryNoPowerTimeByStationID();
		}
		//验证时间是否存在重叠
		function checkTimeOverLap(startArray,endArray) {
		    if(startArray==null || startArray.length<=1) {
		    	return true;
		    }
			var startTimeArr = [];
		    var endTimeArr = [];
		    startTimeArr=startArray;
		    endTimeArr = endArray;
		    var timeE = '',timeS = '';
		    var startTimeArr = startTimeArr.sort();
		    var endTimeArr = endTimeArr.sort();
		    for(var k=1;k<startTimeArr.length;k++){
		        if (startTimeArr[k] <endTimeArr[k-1]){
		            $.messager.alert("提示","时间段存在重叠");
		            return false;
		        }
		    }
		    return true;
		}
		//验证时间是否存在重复
		function checkTimeDouble(newTime,oldTimeArray) {
			var startTime ="";
		    var endTime = "";
		    if(newTime==null ||newTime.length==0) {
		    	return true;
		    }
		    startTime = newTime.NO_POWER_START_TIME;
		    endTime = newTime.NO_POWER_END_TIME;
		    if(oldTimeArray==null || oldTimeArray.length<=1) {
		    	return true;
		    }
		    for(var k=0;k<oldTimeArray.length;k++){
		    	if(oldTimeArray[k].isNew==true) {
		    		continue;
		    	}
		    	var start1 = oldTimeArray[k].NO_POWER_START_TIME;
		    	var start2 = oldTimeArray[k+1].NO_POWER_START_TIME;
		    	var end1 = oldTimeArray[k].NO_POWER_END_TIME;
		    	var end2 = oldTimeArray[k+1].NO_POWER_END_TIME;
		    	if(start1==start2 && end1==end2) {
		            $.messager.alert("提示","时间段重复");
		            return false;
		    	}
		    }
		    return true;
		}
		/**
		 * 检查新增停电时间段是否为空
		 */
		function checkNull(curData) {
			if(curData.TIME_NUM==null||curData.TIME_NUM=='') {
				$.messager.alert("提示","停电时段名称不能为空");
				return false;
			}
			if(curData.NO_POWER_START_TIME==null||curData.NO_POWER_START_TIME=='') {
				$.messager.alert("提示","停电时段开始时间不能为空");
				return false;
			}
			if(curData.NO_POWER_END_TIME==null||curData.NO_POWER_END_TIME=='') {
				$.messager.alert("提示","停电时段结束时间不能为空");
				return false;
			}
			
			return true;
		}
		
		function formateDate(Data) {
			var flag = /\//g;
			var st_index=0;
			var end_index=0;
			st_index = Data.NO_POWER_START_TIME.indexOf("/");
			end_index = Data.NO_POWER_END_TIME.indexOf("/");
			if(st_index>0) {
				Data.NO_POWER_START_TIME = Data.NO_POWER_START_TIME.replace(flag,"-");
				Data.NO_POWER_START_TIME=Data.NO_POWER_START_TIME+":00";
			}
			if(end_index>0) {
				Data.NO_POWER_END_TIME = Data.NO_POWER_END_TIME.replace(flag,"-");
				Data.NO_POWER_END_TIME= Data.NO_POWER_END_TIME+":00";
			}
			return Data;
		}
		/**
		 * 检查修改停电时间段开始时间和结束时间，是否保持一致
		 */
		function checkAllNull(curData) {
			if(curData.NO_POWER_START_TIME==''&&curData.NO_POWER_END_TIME!='') {
				$.messager.alert("提示","结束时间也必须为空");
				return false;
			}
			if(curData.NO_POWER_START_TIME!=''&&curData.NO_POWER_END_TIME=='') {
				$.messager.alert("提示","开始时间也必须为空");
				return false;
			}
			return true;
		}
		
	});
	//有效审核，新控制器ValidationMonitorDataCheckController
	DataValidationController.controller('ValidationMonitorDataCheckController',function($filter,$stateParams,$sce,$scope,$itfreerHttp,$itfreer,$compile,$http,$waterDataCommon,$httpData,$queryObj,$wdp,$rootScope,$state,$formObject,$NavService,OperationStationJobService,$ReportService){
		$NavService.setSelectedTab("DataValidationQuarter.Check");
		$scope.resultDataForSelect=[{VALUE:"0",NAME:"不合格"},{VALUE:"1",NAME:"合格"}];
		$scope.CheckData={};
		 $scope.queryObject={};
	     $scope.queryObject.queryMonitorDataValidation={};
	     $scope.queryObject.queryMonitorDataValidation.STATION_ID="";
	     $scope.queryObject.queryMonitorDataValidation.WATER_TYPE="0";
	     $scope.queryObject.queryMonitorDataValidation.BUILD_STATUS="0";
	     var myDate = new Date();
	     $scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR = myDate.getFullYear();
	     getQuarterStartMonth();
	            //获取当前月的开始月份
	            function  getQuarterStartMonth(){
	            	var now = new Date(); //当前日期 
	            	var nowMonth = now.getMonth()+1; //当前月
	            	var quarterStartMonth = 0; 
	            	if(nowMonth<4){ 
	            	quarterStartMonth = 1; 
	            	} 
	            	if(3<nowMonth && nowMonth<7){ 
	            	quarterStartMonth = 4; 
	            	} 
	            	if(6<nowMonth && nowMonth<10){ 
	            	quarterStartMonth = 7; 
	            	} 
	            	if(nowMonth>9){ 
	            	quarterStartMonth = 10; 
	            	} 
	            	 $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH= quarterStartMonth;
	            	 $scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH=quarterStartMonth+2;
	            }  
	            function parseYearStartMonth(year,month){
	    			var start_month = ''+ month;
	    			
	    			if(start_month.length==1) {
	    				start_month = '0' + start_month;
	    			}
	    			
	    			var start_date = year + '-' + start_month + '-01';
	    			return start_date;
	    		}
	    		
	    		function parseYearEndMonth(year, month){
	    			
	    			var end_day = new Date(year,month,0); 
	    			var endday = '' + end_day.getDate();
	    			
	    			if(endday.length==1){
	    				endday = '0' + endday;
	    			}
	    			var end_month = '' + month;
	    			if(end_month.length==1) {
	    				end_month = '0' + end_month;
	    			}
	    			
	    			var end_date = year + '-' + end_month + '-' + endday;
	    			return end_date;
	    		}
		//获取站点
		$scope.getStation=function(){
			 $scope.queryObject.queryMonitorDataValidation.WWTP_ID=$wdp.viewValue.wwtpDetailParm.WWTPID;
			$waterDataCommon.getPageRows("/OnlineMonitor/station.do","stationDetailList",$scope.queryObject.queryMonitorDataValidation,10,1,function(d){
				//获取下拉所属站点数据
				$wdp.viewValue.StationDataForSelect={};
				$wdp.viewValue.StationDataForSelect.data=d.data;
			});
		};
		$scope.STATION_NAME="";
		$scope.STATION_ID="";
		$scope.getSationname=function(orgid){
			if(orgid=="0"){
				$("#wsclcname li[orgid='"+1+"']").removeClass('selected');
				$("#wsclcname li[orgid='"+0+"']").addClass('selected');
				$scope.STATION_ID=$wdp.viewValue.wwtpDetailParm.STATION_ID;
				
			}
            if(orgid=="1"){
            	$("#wsclcname li[orgid='"+0+"']").removeClass('selected');
            	$("#wsclcname li[orgid='"+1+"']").addClass('selected');
            	$scope.STATION_ID="";
			}
		};
		
		
		//监听左侧参数变化
		$scope.$on('dataPramChanged', function(event, data) {
			$wdp.viewValue.wwtpDetailParm=data;
			$scope.STATION_NAME=$wdp.viewValue.wwtpDetailParm.STATION_NAME;
			$scope.STATION_ID=$wdp.viewValue.wwtpDetailParm.STATION_ID;
			$scope.getCheckData();
	    });
		
		//新建审核记录
		$scope.newDataValidationCheck=function(){
			$scope.CheckData={};
			$itfreer.openWindow('newDataValidationCheck');
		};
		//取消
		$scope.closeNewData=function(){
			$itfreer.closeWindow('newDataValidationCheck');
		};
		//保存
		$scope.saveData=function(CheckData){
			CheckData.ST=CheckData.ST+":00";
			CheckData.ET=CheckData.ET+":00";
			if(CheckData.ST.indexOf('undefined')>=0||CheckData.ET.indexOf('undefined')>=0) {
				$.messager.alert("提示","请选择数据对比时间");
				return;
			}
			CheckData.STATION_CODE=$wdp.viewValue.wwtpDetailParm.STATION_ID;
			$itfreerHttp.save('DATAVALIDATION_QUARTER',CheckData,function(d){
				$scope.getCheckData();
				$itfreer.closeWindow('newDataValidationCheck');
				$.messager.alert("提示","保存成功");
			});
		};
		//编辑
		$scope.editCheck=function(data){
			$scope.CheckData=angular.copy(data);
			$itfreer.openWindow('newDataValidationCheck');
		};
		//删除
		$scope.deleteCheck=function(data){
			$.messager.confirm("确认","确定要删除这条记录吗？",function(r){
				if(r){
					$itfreerHttp.deleteByKey("DATAVALIDATION_QUARTER", {GUID:data.GUID},function(){
						$.messager.alert("提示","删除成功！");
						$scope.getCheckData();
					});
				}
			});
		};
		//查询信息
		$scope.getCheckData=function(){
			if($scope.dataType=='month'&&Number($scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH)>Number($scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH)){
				alert("结束月份不能小于开始月份！");
				return;
			}
			$scope.queryObject.queryMonitorDataValidation.START_TIME = parseYearStartMonth($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR, $scope.queryObject.queryMonitorDataValidation.MEASURE_START_MONTH);
			$scope.queryObject.queryMonitorDataValidation.END_TIME = parseYearEndMonth($scope.queryObject.queryMonitorDataValidation.MEASURE_YEAR, $scope.queryObject.queryMonitorDataValidation.MEASURE_END_MONTH);
			$scope.queryObject.queryMonitorDataValidation.STATION_CODE=$scope.STATION_ID;
			$scope.queryObject.queryMonitorDataValidation.waterType=getWaterType();
			//$scope.queryObject.queryMonitorDataValidation.WWTP_ID=$wdp.viewValue.wwtpDetailParm.WWTPID;
			$waterDataCommon.getPageRows("/DataValidation/getCheckData.do","DataValidationCheckList",$scope.queryObject.queryMonitorDataValidation,100,1,function(d){
			});
		};
		//下载文档
		$scope.downloadDoc=function(val){
			if(val){
				 var arr = new Array();
				 var filesrt="";
				 var filename="";
				 var filepath="";
				 var arry=new Array();
				if(val.indexOf("|") > 0)
				{
					 arr = val.split("|");
					 filesrt=String(arr[arr.length-1].toString().split(":")[0]);
					 filename=String(arr[arr.length-1].toString().split(":")[1]);
					 arry=filesrt.split("WaterMonitor");
					 filepath=String(arry[1]);
					 filename=String(arr[1]);
			    }
				 else{
					 if(val.indexOf(":") > 0){
						 arr = val.split(":");
						 filesrt=String(arr[0]);
						 arry=filesrt.split("WaterMonitor");
						 filepath=String(arry[1]);
						 filename=String(arr[1]);
					 }
					 else{
						 return;
					 }

				 }
				//$scope.furl="/WaterMonitor/plupload/download.do?filePath="+filepath+"&fileName="+filename;
				window.open("/WaterMonitor/plupload/download.do?filePath="+filepath+"&fileName="+filename);
			}
			else{
				$.messager.alert('系统提示',"无文档!");
			}
		};
		if($wdp.viewValue.wwtpDetailParm){
			$scope.STATION_NAME=$wdp.viewValue.wwtpDetailParm.STATION_NAME;
			$scope.STATION_ID=$wdp.viewValue.wwtpDetailParm.STATION_ID;
			$scope.getCheckData();
		}
	});	
}(window, angular));